package bmptest.bmp.controller.login;

import bmptest.bmp.common.realm.LoginRealm;
import bmptest.bmp.entity.SysUser;
import bmptest.bmp.result.Result;
import bmptest.bmp.service.login.LoginService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @author lyq
 * @date 2021/9/6 9:38
 * 登录
 */

@Controller
public class LoginController {
    @Autowired
    private LoginService loginService;

    public static String passwordLogin;

    public static String getPasswordLogin() {
        return passwordLogin;
    }

    @Autowired
    public  RedisTemplate<String,String> redisTemplate;

    @CrossOrigin
    @PostMapping(value = "api/login")
    @ResponseBody
    public Result login(@RequestBody SysUser requestSysUser, HttpSession session, HttpServletRequest request) {
        //判断验证是否通过
        Boolean isValidate = this.verifyUserPass(requestSysUser);
        if(isValidate){
            SysUser u = loginService.findByUsername(requestSysUser.getUser_name());
            String uid = u.getUser_id();
            String uname = u.getUser_name();
            redisTemplate.setKeySerializer(RedisSerializer.string());
            redisTemplate.opsForValue().set("uid",uid);
            redisTemplate.opsForValue().set("uname",uname);
            return new Result(200);
        }else{
            String message = "账号密码错误";
            return new Result(400);
        }
    }

    /**
     * @author lyq
     * @date 2021/9/8 14:46
     * 通过shiro验证账号密码
     */
    private Boolean verifyUserPass(SysUser sysuser){
        //根据用户名查询加密后的密码
        passwordLogin = loginService.findByUsername(sysuser.getUser_name()).getPassword();
        //如果数据库中输入的账户名存在
        if(loginService.countUsername(sysuser.getUser_name())>=1){
            //创建安全管理器
            DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
            //注入realm
            LoginRealm loginRealm = new LoginRealm();
            //设置reaml使用hash凭证器
            HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
            //使用md5加密算法
            credentialsMatcher.setHashAlgorithmName("md5");
            //散列次数
            credentialsMatcher.setHashIterations(1024);
            loginRealm.setCredentialsMatcher(credentialsMatcher);
            defaultSecurityManager.setRealm(loginRealm);
            //将安全管理器注入安全工具
            SecurityUtils.setSecurityManager(defaultSecurityManager);
            //通过安全工具获取subject
            Subject subject = SecurityUtils.getSubject();
            //创建token
            UsernamePasswordToken token = new UsernamePasswordToken(sysuser.getUser_name(),sysuser.getPassword());
            try{
                subject.login(token);
                System.out.println(subject.isAuthenticated());
                return true;
            }catch(UnknownAccountException e){
                e.printStackTrace();
                System.out.println("用户名错误");
                return false;
            }catch(IncorrectCredentialsException e){
                e.printStackTrace();
                System.out.println("密码错误");
                return false;
            }
        }else{
            System.out.println("没有此账户");
            return false;
        }
    }

}
